// 路由守卫，用于检查登录状态
import authManager from './auth.js'

// 需要登录的页面列表
const needLoginPages = ['qmy_user/user/userPersonal', 'pages/publish/article', 'pages/publish/activity', 'pages/publish/notice', 'pages/detail/messageDetail', 'qmy_user/user/myPage', 'qmy_user/user/eventManagement', 'qmy_user/user/lnformationManagement', 'qmy_user/user/myActivities', 'qmy_user/user/authentication', 'qmy_user/user/myWallet', 'qmy_user/user/myCart', 'qmy_user/user/myCollect', 'qmy_user/user/address/list', 'qmy_user/user/address/add', 'qmy_user/user/address/edit', 'qmy_user/user/order/list', 'qmy_user/user/order/detail', 'qmy_user/user/order/refund', 'qmy_user/user/order/refundDetail', 'qmy_user/user/order/evaluate', 'qmy_user/user/order/evaluateList', 'pages/detail/submitOrder', 'pages/detail/pay-desk']

// 检查当前页面是否需要登录
function checkPageNeedLogin(route) {
    // 移除开头的斜杠
    const cleanRoute = route.replace(/^\//, '')
    return needLoginPages.some(page => cleanRoute.includes(page))
}

// 路由拦截器
function routeIntercept() {
    // 拦截 navigateTo
    const originalNavigateTo = uni.navigateTo
    uni.navigateTo = function (options) {
        if (checkPageNeedLogin(options.url)) {

            console.log('需要登录', !authManager.isLoggedIn())

            if (!authManager.isLoggedIn()) {
                uni.showToast({
                    title: '请先登录', icon: 'none'
                })
                setTimeout(() => {
                    uni.navigateTo({
                        url: '/qmy_user/login'
                    })
                }, 500)
                return
            }
        }
        return originalNavigateTo.call(this, options)
    }

    // 拦截 redirectTo
    const originalRedirectTo = uni.redirectTo
    uni.redirectTo = function (options) {
        if (checkPageNeedLogin(options.url)) {
            if (!authManager.isLoggedIn()) {
                uni.showToast({
                    title: '请先登录', icon: 'none'
                })
                setTimeout(() => {
                    uni.navigateTo({
                        url: '/qmy_user/login'
                    })
                }, 500)
                return
            }
        }
        return originalRedirectTo.call(this, options)
    }

    // 拦截 reLaunch
    const originalReLaunch = uni.reLaunch
    uni.reLaunch = function (options) {
        if (checkPageNeedLogin(options.url)) {
            if (!authManager.isLoggedIn()) {
                uni.showToast({
                    title: '请先登录', icon: 'none'
                })
                setTimeout(() => {
                    uni.navigateTo({
                        url: '/qmy_user/login'
                    })
                }, 500)
                return
            }
        }
        return originalReLaunch.call(this, options)
    }
}

export default {
    install: routeIntercept, checkPageNeedLogin
}
